{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '3'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate):\n",
    "        \n",
    "        def cells(reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer,reuse=reuse)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        \n",
    "        def forward(x, y, reuse = False):\n",
    "            batch_size = tf.shape(x)[0]\n",
    "            X_seq_len = tf.count_nonzero(x, 1, dtype = tf.int32)\n",
    "            Y_seq_len = tf.count_nonzero(y, 1, dtype = tf.int32)\n",
    "            with tf.variable_scope('model',reuse=reuse):\n",
    "                encoder_embedded = tf.nn.embedding_lookup(embeddings, x)\n",
    "                decoder_embedded = tf.nn.embedding_lookup(embeddings, y)\n",
    "                rnn_cells = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)])\n",
    "                last_output, last_state = tf.nn.dynamic_rnn(rnn_cells, encoder_embedded,\n",
    "                                                  sequence_length=X_seq_len,\n",
    "                                                  dtype = tf.float32)\n",
    "                \n",
    "            with tf.variable_scope(\"decoder\",reuse=reuse):\n",
    "                \n",
    "                attention_mechanism = tf.contrib.seq2seq.LuongAttention(num_units = size_layer, \n",
    "                                                                    memory = last_output)\n",
    "                rnn_cells = tf.contrib.seq2seq.AttentionWrapper(\n",
    "                    cell = tf.nn.rnn_cell.MultiRNNCell([cells() for _ in range(num_layers)]), \n",
    "                    attention_mechanism = attention_mechanism,\n",
    "                    attention_layer_size = size_layer)\n",
    "                \n",
    "                initial_state = rnn_cells.zero_state(batch_size, tf.float32).clone(cell_state=last_state)\n",
    "                outputs, _ = tf.nn.dynamic_rnn(rnn_cells, decoder_embedded, \n",
    "                                               sequence_length=Y_seq_len,\n",
    "                                               initial_state = initial_state,\n",
    "                                               dtype = tf.float32)\n",
    "                \n",
    "                return tf.layers.dense(outputs,vocab_size)\n",
    "            \n",
    "        main = tf.strided_slice(self.X, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        self.training_logits = forward(self.X, decoder_input, reuse = False)\n",
    "        \n",
    "        self.training_logits = self.training_logits[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        self.training_logits = pad_second_dim(self.training_logits, tf.reduce_max(self.Y_seq_len))\n",
    "            \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))\n",
    "        \n",
    "        initial_ids = tf.fill([batch_size], GO)\n",
    "        def symbols_to_logits(ids):\n",
    "            x = tf.contrib.seq2seq.tile_batch(self.X, 1)\n",
    "            logits = forward(x, ids, reuse = True)\n",
    "            return logits[:, tf.shape(ids)[1]-1, :]\n",
    "        \n",
    "        final_ids, final_probs, _ = beam_search.beam_search(\n",
    "            symbols_to_logits,\n",
    "            initial_ids,\n",
    "            1,\n",
    "            tf.reduce_max(self.X_seq_len),\n",
    "            vocab_size,\n",
    "            0.0,\n",
    "            eos_id = EOS)\n",
    "        \n",
    "        self.fast_result = final_ids"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-e46d48962ce9>:11: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-e46d48962ce9>:29: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-e46d48962ce9>:32: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-e46d48962ce9>:49: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.Dense instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/layers/core.py:187: Layer.apply (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.__call__` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensor2tensor/utils/beam_search.py:745: to_float (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[[    1, 31355, 31355,  8391,  8391,  8391, 20320, 20320, 20320,\n",
       "          20320, 24333, 24333, 24333, 20118,  3659,  3461, 22930, 27599,\n",
       "          27599, 15847, 14110,  2017,  2017,  3775,  3775, 30113,  7346,\n",
       "           7346,  7346,  9751,  9751, 14563, 14563, 14563, 14563, 12853,\n",
       "          23246]],\n",
       " \n",
       "        [[    1,  7163, 30412, 30412, 30412, 30412, 18203, 18203,  1554,\n",
       "           1554,  1554, 31635, 31635, 31635,  2533,  2533,  2533,  2533,\n",
       "          26266,  9881,  9881,  9881,  9881,  9881, 14189, 14189, 14189,\n",
       "          14189,  4451,  4451, 23314, 23314, 23314, 23314, 23314, 23314,\n",
       "          23314]],\n",
       " \n",
       "        [[    1, 13562, 13562, 13562, 20672, 23171, 23171,   382,   382,\n",
       "           9725,  9725, 13189, 13189,   382, 20454,   382, 20454, 20210,\n",
       "          20210, 21113, 21113, 21113, 17886, 12136, 12136, 24183, 24183,\n",
       "          30130, 30130, 24071, 24071, 11760, 11760, 10310, 10310, 10431,\n",
       "          10431]],\n",
       " \n",
       "        [[    1, 12254,  4818,  4818, 25832, 25832, 25832, 22218, 22218,\n",
       "          22218, 23526, 22218,  2719, 30227, 30227,  5097,  5097, 19840,\n",
       "           3066,  3066, 10046, 10046, 10046, 21592, 21592, 25990, 25990,\n",
       "          19840, 19840, 19840, 19840, 13620, 13620, 22695, 22695, 22695,\n",
       "          22695]],\n",
       " \n",
       "        [[    1, 20135, 20135, 22087, 22087, 31451, 31451, 21209, 21209,\n",
       "          21209,  1943,  1943, 28068, 28068, 12894,  7205,  7205,  7205,\n",
       "          13823, 13823, 13823, 13823,  4392,  4392,  4392,  4392, 27421,\n",
       "          26466, 26466, 28057, 28057, 28057, 14375, 14375, 14375, 20963,\n",
       "          27498]],\n",
       " \n",
       "        [[    1, 27138, 27138, 27138, 25010, 25010, 25010, 20380, 20380,\n",
       "          20380, 19811, 19811, 19811, 19811, 19811, 15875, 19811,  6514,\n",
       "           6514, 24676, 24676, 24676,  4520,  4520,  4520, 28453, 28453,\n",
       "          28453, 23465, 29413, 29413, 29413, 29413, 29413, 20898, 30023,\n",
       "          21144]],\n",
       " \n",
       "        [[    1, 10318, 17478, 18330,  8732,  8732, 16136, 30655,  8732,\n",
       "          22365, 14736, 14736, 14736, 14736,  1542,  1198,  1198,  1198,\n",
       "           8456, 24803, 24803, 24803, 21390,  7640,  4841,  4841, 10505,\n",
       "          31051, 31051,  7638,  7638,  7029,  7029,  8346,  8346,  8346,\n",
       "          14173]],\n",
       " \n",
       "        [[    1, 21494, 15133, 26372, 26372, 26372, 15071,  3980,    62,\n",
       "             62,    62,    62,  3019,  3019,  3019,  3019,   789,   789,\n",
       "            789, 15274, 15274, 23171, 23171, 23171, 12225, 12225, 12225,\n",
       "           4831,  4831,  4831,  5821, 10572, 10572,  5821, 15126, 19280,\n",
       "          24388]],\n",
       " \n",
       "        [[    1, 30042, 30042, 10888,  4595, 19505, 11539, 11539, 11539,\n",
       "          11539, 17978, 11539, 17978, 11539, 26835,  1646, 26835, 16042,\n",
       "          16042, 25072, 12932, 12932, 15892,  4584, 31252, 24348,  1012,\n",
       "           1012,  1012, 19455, 19455, 19455,  5586,  5586,  5586,  4118,\n",
       "           4118]],\n",
       " \n",
       "        [[    1, 12846,  5753,  5753,  9741,  9741,  1927,  1927,  4514,\n",
       "          22473, 22473, 22473, 22473, 19232, 16900, 16900, 13423, 12375,\n",
       "          12375, 18120, 18120, 18120, 17560, 17560, 17560, 17560, 27177,\n",
       "          27177, 25701, 14261, 14261, 14261, 14261, 25729, 25729, 25729,\n",
       "          21432]]], dtype=int32), 10.372889, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.131, cost=6.32]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.28it/s, accuracy=0.129, cost=6.01]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 6.871849, training avg acc 0.116480\n",
      "epoch 1, testing avg loss 6.248673, testing avg acc 0.141463\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.151, cost=5.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.44it/s, accuracy=0.134, cost=5.78]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 5.905830, training avg acc 0.148919\n",
      "epoch 2, testing avg loss 5.879802, testing avg acc 0.151962\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:15<00:00,  2.81it/s, accuracy=0.161, cost=4.91]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.42it/s, accuracy=0.14, cost=5.79] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg loss 5.428575, training avg acc 0.162819\n",
      "epoch 3, testing avg loss 5.749996, testing avg acc 0.152502\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.178, cost=4.67]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.43it/s, accuracy=0.156, cost=5.79]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg loss 5.108738, training avg acc 0.174096\n",
      "epoch 4, testing avg loss 5.716868, testing avg acc 0.154437\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.191, cost=4.43]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.46it/s, accuracy=0.124, cost=5.67]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 4.870669, training avg acc 0.183328\n",
      "epoch 5, testing avg loss 5.634433, testing avg acc 0.156762\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.207, cost=4.13]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.43it/s, accuracy=0.129, cost=5.71]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg loss 4.682782, training avg acc 0.191978\n",
      "epoch 6, testing avg loss 5.655763, testing avg acc 0.154523\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.24, cost=3.91] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.51it/s, accuracy=0.129, cost=5.69]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg loss 4.545386, training avg acc 0.199570\n",
      "epoch 7, testing avg loss 5.683060, testing avg acc 0.156376\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.229, cost=3.85]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.42it/s, accuracy=0.14, cost=5.76] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg loss 4.435296, training avg acc 0.206033\n",
      "epoch 8, testing avg loss 5.766815, testing avg acc 0.153452\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:15<00:00,  2.81it/s, accuracy=0.247, cost=3.78]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.47it/s, accuracy=0.108, cost=5.74]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg loss 4.337311, training avg acc 0.212899\n",
      "epoch 9, testing avg loss 5.791104, testing avg acc 0.154626\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.251, cost=3.72]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.46it/s, accuracy=0.129, cost=6.02]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 4.258332, training avg acc 0.218385\n",
      "epoch 10, testing avg loss 5.844195, testing avg acc 0.154280\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:15<00:00,  2.82it/s, accuracy=0.261, cost=3.61]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.53it/s, accuracy=0.108, cost=6.11]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg loss 4.195721, training avg acc 0.222990\n",
      "epoch 11, testing avg loss 5.889951, testing avg acc 0.152452\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:17<00:00,  2.81it/s, accuracy=0.254, cost=3.69]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.43it/s, accuracy=0.0968, cost=6.1]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg loss 4.207453, training avg acc 0.219987\n",
      "epoch 12, testing avg loss 5.886508, testing avg acc 0.150119\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.229, cost=3.78]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.45it/s, accuracy=0.118, cost=5.98]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 4.132468, training avg acc 0.226418\n",
      "epoch 13, testing avg loss 5.989252, testing avg acc 0.148968\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:16<00:00,  2.81it/s, accuracy=0.266, cost=3.56]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.44it/s, accuracy=0.102, cost=6]   \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg loss 4.153476, training avg acc 0.222842\n",
      "epoch 14, testing avg loss 5.917052, testing avg acc 0.153155\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:13<00:00,  2.82it/s, accuracy=0.259, cost=3.49]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.43it/s, accuracy=0.124, cost=6.07]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 4.086502, training avg acc 0.229716\n",
      "epoch 15, testing avg loss 5.935670, testing avg acc 0.154852\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:12<00:00,  2.83it/s, accuracy=0.285, cost=3.36]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.56it/s, accuracy=0.124, cost=6.14]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 3.971476, training avg acc 0.241584\n",
      "epoch 16, testing avg loss 5.996438, testing avg acc 0.152914\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:07<00:00,  2.86it/s, accuracy=0.284, cost=3.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.54it/s, accuracy=0.129, cost=5.99]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 3.972175, training avg acc 0.240528\n",
      "epoch 17, testing avg loss 6.041375, testing avg acc 0.151317\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.285, cost=3.42]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.44it/s, accuracy=0.118, cost=6.2] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 3.926377, training avg acc 0.245631\n",
      "epoch 18, testing avg loss 6.093192, testing avg acc 0.151945\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:14<00:00,  2.82it/s, accuracy=0.262, cost=3.56]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.48it/s, accuracy=0.113, cost=6.4] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 3.940612, training avg acc 0.243879\n",
      "epoch 19, testing avg loss 6.119932, testing avg acc 0.147849\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [09:10<00:00,  2.84it/s, accuracy=0.223, cost=3.96]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:06<00:00,  6.58it/s, accuracy=0.124, cost=6.27]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 3.982630, training avg acc 0.239038\n",
      "epoch 20, testing avg loss 6.267588, testing avg acc 0.141151\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [02:43<00:00,  4.09s/it]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)[:,0,:]\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.01888038"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
